package com.example.springMVC.controller;


import com.example.springMVC.commons.Result;
import com.example.springMVC.commons.ServiceException;
import com.example.springMVC.pojo.User;
import com.example.springMVC.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @ResponseBody
    @RequestMapping("/login")
    public Result login(User user, HttpSession session) throws Exception {
        User u = userService.login(user);
        session.setAttribute("user", u);
        return Result.success();
    }

    @ResponseBody
    @RequestMapping("/userList")
    public Result userList(Integer currentPage, @RequestParam(required = false) Integer roleId, @RequestParam(required = false) String userName) {
        PageInfo<User> userList = userService.userList(currentPage, roleId, userName);
        return Result.success(userList);
    }

    @ResponseBody
    @RequestMapping("/logout")
    public Result logout(User user, HttpSession session) {
        session.removeAttribute("user");
        return Result.success();
    }

    @ResponseBody
    @RequestMapping("/addUser")
    public Result addUser(User user, HttpSession session) throws ServiceException {
        User loginUser = (User) session.getAttribute("user");
        user.setCreatedBy(loginUser.getId());
        boolean fale = userService.addUser(user);
        return Result.success(fale);
    }

    @ResponseBody
    @RequestMapping("/getUserByCode")
    public Result getUserByCode(String userCode) {
        User user = userService.getUserByCode(userCode);
        return Result.success(user);
    }

    @ResponseBody
    @DeleteMapping("{userId}")
    public Result deleteUser(@PathVariable Long userId) {
        boolean fale = userService.deleteUser(userId);
        return Result.success(fale);
    }

    @ResponseBody
    @PostMapping("{userid}")
    public Result updateUserById(@PathVariable long userid, User user) throws ServiceException {
        user.setId(userid);
        boolean fale = userService.updateUserById(user);
        return Result.success(fale);
    }
    @ResponseBody
    @GetMapping("{userId}")
    public Result getUserById(@PathVariable long userId){
        User user =  userService.getUserById(userId);
        return Result.success(user);
    }

//    @RequestMapping("/mvc2")
//    public ModelAndView handleRequestInternal2(){
//        ModelAndView mvc = new ModelAndView();
////        为mvc添加内容
//        mvc.addObject("msg","hello,SpringMVC");
////        内容是index.jsp
//        mvc.setViewName("index");
////        返回一个ModelAndView
//        return mvc;
//    }
}
